package repository

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mts/log_srv/internal/domain"
	"mts/log_srv/internal/repository/dao"
	"time"
)

type LogRepo interface {
	SaveLog(logData domain.Logs) error
	List(ctx *gin.Context, page, size int) ([]*domain.Logs, error)
}
type GormLogRepository struct {
	logs dao.LogsDao
}

func (g GormLogRepository) List(ctx *gin.Context, page, size int) ([]*domain.Logs, error) {
	list, err := g.logs.List(ctx, page, size)
	if err != nil {
		zap.S().Errorf("获取日志失败:%s", err)
	}

	var logs []*domain.Logs
	for _, v := range list {
		// 解析时间字符串
		toDomain := g.entityToDomain(*v)
		logs = append(logs, &toDomain)
	}
	return logs, err
}

func (g GormLogRepository) SaveLog(logData domain.Logs) error {
	// 这里可以替换为实际的数据库操作
	logsInfo := g.toEntity(logData)
	// 例如使用 GORM 或 SQLx 进行数据库操作
	err := g.logs.SaveLog(&logsInfo) // 传递指针
	if err != nil {
		zap.S().Errorf("写入日志失败 : %v", logsInfo)
		return err
	}
	zap.S().Infof("写入日志成功: %v", logsInfo)
	return nil
}

func NewLogRepo(logs dao.LogsDao) LogRepo {
	return &GormLogRepository{
		logs: logs,
	}
}

func (g GormLogRepository) entityToDomain(d dao.Logs) domain.Logs {
	time := d.Timestamp.Format("2006-01-02 15:04:05")
	log := domain.Logs{
		ID:        d.ID,
		UserID:    d.UserID,
		Action:    d.Action,
		Type:      d.Type,
		Timestamp: time,
		Details:   d.Details,
	}
	return log
}
func (g GormLogRepository) toEntity(d domain.Logs) dao.Logs {
	t, err := time.Parse(time.RFC3339, d.Timestamp)
	if err != nil {
		zap.S().Errorf("时间解析失败: %s", err)
		return dao.Logs{}
	}
	log := dao.Logs{
		ID:         d.ID,
		UserID:     d.UserID,
		Action:     d.Action,
		Type:       d.Type,
		Timestamp:  t,
		Details:    d.Details,
		LanguageID: d.LanguageID,
	}
	return log
}
